package xxl.signals.impl 
{
	import flash.utils.getTimer;
	import xxl.signals.api.ILazySignal;
	import xxl.signals.impl.valuelists.ArrayValueListAscend;
	import xxl.signals.util.SignalUtil;
	/**
	 * ...
	 * @author XXL
	 */
	public class LazySignal extends PrioritySignal implements ILazySignal
	{
		protected var valueObjectsList:ArrayValueListAscend = ArrayValueListAscend.NIL;
		
		public function LazySignal(...valueClasses) 
		{
			valueClasses = (valueClasses.length == 1 && valueClasses[0] is Array) ? valueClasses[0]:valueClasses;
			super(valueClasses);
		}
		
		override public function dispatch(...valueObjects):void 
		{
			SignalUtil.VerifyDispatch(valueClasses, valueObjects);
			valueObjectsList = valueObjectsList.append(valueObjects);
		}
		
		/* INTERFACE xxl.signals.core.ILazySignal */
		
		public function activate(limitTime:int = 0):Boolean 
		{
			var process:ArrayValueListAscend = valueObjectsList;
			if (process.nonEmpty)
			{
				const time:int = getTimer();
				if (sortFlag)
				{
					sortFlag = false;
					slots = slots.sortOn("priority", Array.NUMERIC);
				}
				while (process.nonEmpty)
				{
					const valueObjects:Array = process.tail;
					process = process.head;
					for (var i:int = slots.length; i--; )
					{
						slots[i].execute(valueObjects);
					}
					if ((limitTime > 0) && (limitTime < (getTimer() - time)))
					{
						break;
					}
				}
				if (process.nonEmpty)
				{
					process.first = valueObjectsList.first;
					valueObjectsList = process;
					return false;
				}
				else
				{
					valueObjectsList = ArrayValueListAscend.NIL;
					return true;
				}
			}
			return true;
		}
		
	}

}